package com.transcoachapp;

import java.util.ArrayList;

import com.transcoachapp.adapter.AutoCompleteAdapter;
import com.transcoachapp.adapter.AutoCompleteRouteAdapter;
import com.transcoachapp.data.Bus;
import com.transcoachapp.data.Station;
import com.transcoachapp.database.DataBaseHelper;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;

public class WhereIsMyBusFragment extends Fragment {
	private AutoCompleteTextView editRoute;
	private AutoCompleteRouteAdapter routeAdapter;
	public Bus selectedRoute;
	public static DataBaseHelper db;
	private Button btn;
	
	@Override 
	public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        setUserVisibleHint(true);
    }
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = (LinearLayout)inflater.inflate(R.layout.activity_where_is_my_bus_fragment, container, false);
		editRoute = (AutoCompleteTextView) v.findViewById(R.id.autoCompleteRoute);
		
		db=new DataBaseHelper(this.getActivity().getApplicationContext());	
		ArrayList<Bus> busList=db.getBusList("");
		
		routeAdapter =new AutoCompleteRouteAdapter(this.getActivity(),R.layout.auto_complete_route ,R.id.autoCompleteRoute, busList);
		editRoute.setAdapter(routeAdapter);
		
		editRoute.setOnItemClickListener(routeClickListener);
		//fromEdit.setThreshold(1);
	    
		btn = (Button) v.findViewById(R.id.whereIsMyBusButton);
		btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Log.i("routCode", selectedRoute.getRouteCode());
				Intent intent = new Intent();
                intent.setClass(getActivity(), WhereIsBusActivityList.class);
                intent.putExtra("routeCode",selectedRoute.getRouteCode());
				startActivity(intent);	
			}
			
		});
		if (container == null) {
            return null;
        }
		return v;
	}
	private OnItemClickListener routeClickListener = new 
	         OnItemClickListener() {	           
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					selectedRoute=(Bus)arg0.getItemAtPosition(arg2);
					Log.i("select: ", selectedRoute.getRouteName()+ " - "+ selectedRoute.getRouteCode());
				}
				
	};
}
